<template>
  <el-row :gutter="20" class="app-container">
    <Splitpanes>
      <pane size="16" v-if="$auth.hasRoleOr(['admin','manager','fishingceo'])">
        <el-col>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
      </pane>

      <pane :size="$auth.hasRoleOr(['admin','manager','fishingceo']) ? 84 : 100">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="鱼塘" prop="pondId">
            <PondSelect
              v-model="queryParams.pondId"
              :dept-id="queryParams.deptId"
              placeholder="选择鱼塘"
              width="120px"
              @change="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['pond:fishrecord:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['pond:fishrecord:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['pond:fishrecord:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['pond:fishrecord:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="fishrecordList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="id" align="center" prop="id" />
          <el-table-column label="鱼塘" align="center" prop="pondName" />
          <el-table-column label="鱼种类" align="center" prop="fishName" />
          <el-table-column label="流转类型" align="center" prop="flowType">
            <template #default="scope">
              {{
                scope.row.flowType == 1
                  ? "买鱼"
                  : scope.row.flowType == 2
                  ? "卖鱼"
                  : "转塘"
              }}
            </template>
          </el-table-column>
          <el-table-column label="重量/斤" align="center" prop="weight" />
          <el-table-column
            label="实际单价/元"
            align="center"
            prop="pricePerKg"
          />
          <el-table-column
            label="记录时间"
            align="center"
            prop="flowTime"
            width="150"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.flowTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="供货商名称"
            align="center"
            prop="customerOrSupplier"
          />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column
            label="操作"
            align="center"
            width="130"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['pond:fishrecord:edit']"
                >修改</el-button
              >
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['pond:fishrecord:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改鱼流转记录对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
          <el-form
            ref="fishrecordRef"
            :model="form"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="所属钓场" prop="deptId">
              <DeptSelect
                v-model="form.deptId"
                @change="handleDeptChange"
              />
            </el-form-item>
            <el-form-item label="鱼塘" prop="pondId">
              <PondSelect
                v-model="form.pondId"
                :dept-id="form.deptId"
                @change="handlePondChange"
              />
            </el-form-item>
            <el-form-item label="鱼种类">
              <el-select v-model="form.fishTypeId" placeholder="选择流鱼种类" style="width: 100%">
                <el-option
                  v-for="item in fishOptionList"
                  :label="item.fishName"
                  :value="item.fishId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="流转类型" prop="flowType">
              <el-select v-model="form.flowType" placeholder="选择流转类型">
                <el-option label="进鱼" :value="1"> </el-option>
                <el-option label="出鱼" :value="2"> </el-option>
                <el-option label="转塘" :value="3"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="转入鱼塘"
              v-if="form.flowType == 3"
              prop="targetPondId"
            >
              <el-select v-model="form.targetPondId" placeholder="选择转入鱼塘" style="width: 100%">
                <el-option
                  v-for="item in formPondOptionList"
                  :key="item.pondId"
                  :label="item.pondName"
                  :value="item.pondId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="重量" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入重量" />
            </el-form-item>
            <el-form-item label="实际单价" prop="pricePerKg">
              <el-input
                v-model="form.pricePerKg"
                placeholder="请输入实际单价"
              />
            </el-form-item>
            <el-form-item label="记录时间" prop="flowTime">
              <el-date-picker
                clearable
                v-model="form.flowTime"
                format="YYYY/MM/DD"
                type="date"
                placeholder="请选择记录时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="供货商名称" prop="customerOrSupplier">
              <el-input
                v-model="form.customerOrSupplier"
                placeholder="请输入供货商名称"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </pane>
    </Splitpanes>
  </el-row>
</template>

<script setup name="Fishrecord">
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";

import {
  listFishrecord,
  getFishrecord,
  delFishrecord,
  addFishrecord,
  updateFishrecord,
} from "@/api/pond/fishrecord";
import { fishOptions } from "@/api/pond/fishtype";
import { pondOptions } from "@/api/pond/pond";
import { onMounted, watch } from "vue";
import { useDeptTree } from "@/utils/deptTreeUtils";
import PondSelect from "@/components/PondSelect/index.vue";
import DeptSelect from "@/components/DeptSelect/index.vue";
const { proxy } = getCurrentInstance();

const fishrecordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 使用部门树工具
const {
  deptOptions,
  enabledDeptOptions,
  getDeptTree,
  handleFormDeptNodeClick,
  handleSidebarDeptNodeClick,
} = useDeptTree();

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pondId: null,
    fishTypeId: null,
    flowType: null,
    weight: null,
    pricePerKg: null,
    flowTime: null,
    customerOrSupplier: null,
    deptId: undefined,
  },
  rules: {
    deptId: [{ required: true, message: "所属钓场不能为空", trigger: "blur" }],
    pondId: [{ required: true, message: "鱼塘不能为空", trigger: "blur" }],
    targetPondId: [
      { required: true, message: "转入的鱼塘不能为空", trigger: "blur" },
    ],
    flowType: [
      { required: true, message: "流转类型不能为空", trigger: "change" },
    ],
    weight: [{ required: true, message: "重量不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

const fishOptionList = ref(null);
const pondOptionList = ref(null);
const formPondOptionList = ref([]);

function getOptions() {
  fishOptions().then((response) => {
    fishOptionList.value = response.rows;
  });
  pondOptions(queryParams.value).then((response) => {
    pondOptionList.value = response.rows;
  });
}

/** 查询鱼流转记录列表 */
function getList() {
  loading.value = true;
  listFishrecord(queryParams.value).then((response) => {
    fishrecordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    pondId: null,
    deptId: undefined,
    targetPondId: null,
    fishTypeId: null,
    bindFinanceRecord: 0,
    flowType: null,
    weight: null,
    pricePerKg: null,
    flowTime: null,
    customerOrSupplier: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  formPondOptionList.value = [];
  proxy.resetForm("fishrecordRef");
}
/** 表单中的部门树节点点击事件 */
function handleFormDeptNodeClickLocal(data, node, e) {
  handleFormDeptNodeClick(data, node, e, (deptId) => {
    form.value.deptId = deptId;
    // 当部门改变时，重新加载对应的鱼塘列表
    if (deptId) {
      const params = {
        pageNum: 1,
        pageSize: 10,
        deptId: deptId,
      };
      pondOptions(params).then((response) => {
        formPondOptionList.value = response.rows || [];
        form.value.pondId = null; // 清空鱼塘选择
        form.value.targetPondId = null; // 清空转入鱼塘选择
      });
    } else {
      formPondOptionList.value = [];
      form.value.pondId = null;
      form.value.targetPondId = null;
    }
  }, proxy, 'deptTreeSelectRef');
}

/** 侧边栏部门树节点单击事件 */
function handleNodeClick(data) {
  handleSidebarDeptNodeClick(data, (deptId) => {
    queryParams.value.deptId = deptId;
    handleQuery();
  });
}

/** 表单中部门选择变化事件 */
function handleDeptChange(deptId) {
  // 当部门改变时，可以在这里添加相关逻辑
  console.log('选择的部门ID:', deptId);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 鱼塘选择变化事件 */
function handlePondChange(pondId) {
  // 可以在这里添加鱼塘变化后的逻辑
  console.log('选择的鱼塘ID:', pondId);
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 设置默认部门为左侧树选中的部门
  form.value.deptId = queryParams.value.deptId;
  // 如果有选中的部门，获取对应的鱼塘列表
  if (form.value.deptId) {
    const params = {
      pageNum: 1,
      pageSize: 10,
      deptId: form.value.deptId,
    };
    pondOptions(params).then((response) => {
      formPondOptionList.value = response.rows || [];
    });
  }
  open.value = true;
  title.value = "添加鱼流转记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getFishrecord(_id).then((response) => {
    form.value = response.data;
    
    // 如果有部门ID，加载对应的鱼塘列表
    if (form.value.deptId) {
      const params = {
        pageNum: 1,
        pageSize: 10,
        deptId: form.value.deptId,
      };
      pondOptions(params).then((pondResponse) => {
        formPondOptionList.value = pondResponse.rows || [];
      });
    }

    open.value = true;
    title.value = "修改鱼流转记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["fishrecordRef"].validate((valid) => {
    if (valid) {
      if (form.value.flowType != 3) {
        form.value.bindFinanceRecord = 1;
      } else {
        form.value.bindFinanceRecord = 0;
      }
      if (form.value.id != null) {
        updateFishrecord(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFishrecord(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除鱼流转记录编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delFishrecord(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "pond/fishrecord/export",
    {
      ...queryParams.value,
    },
    `fishrecord_${new Date().getTime()}.xlsx`
  );
}

watch(
  open,
  (newValue) => {
    if (newValue) {
      getOptions();
    }
  },
  { immediate: true }
);

onMounted(() => {
  getOptions();
});

getDeptTree();
getList();
</script>
